// 百度地图API功能
var map = new BMap.Map("bmap", {minZoom: 9, maxZoom: 16});    // 创建Map实例
var mapStyle = {style: "midnight"};
map.setMapStyle(mapStyle);

// TODO 改成配置的
// var cityName = '安庆市';
// var centerPoint = new BMap.Point('117.062941', '30.530056');
// var cityName = '合肥市';
// var centerPoint = new BMap.Point('117.282303', '31.857299');
var cityName = '马鞍山市';
var centerPoint = new BMap.Point('118.515018', '31.667906'); //118.515018,31.667906

map.setCurrentCity(cityName);
map.centerAndZoom(centerPoint, 11);  //设置中心点坐标和地图级别
map.enableScrollWheelZoom(true);     //开启鼠标滚轮缩放

// 限制拖动区域，在线地图可以注释掉 TODO 改成配置的
// initMapRestrict();

let parent = null;
let data = {};
let roomMarker = null;
let deviceMarkers = [];
let alarmOverlayMap = [];

function onGpsPick(p, callback) {
  if (p) {
    let arr = p.split(',');
    map.panTo(new BMap.Point(arr[0], arr[1]));
  }

  //单击获取点击的经纬度
  map.addEventListener('click', function (e) {
    const position = e.point.lng + ',' + e.point.lat;
    callback(position);
  });
}

/**
 * 限制拖动区域
 */
function initMapRestrict() {
  var strictBounds = new BMap.Bounds(new BMap.Point(116.18102, 29.58229), new BMap.Point(118.213921, 31.189235));//sw西南,ne东北
  map.addEventListener("dragging", function () {
    var bounds = map.getBounds();
    var sw = bounds.getSouthWest();
    var ne = bounds.getNorthEast();
    var strictSw = strictBounds.getSouthWest();
    var strictNe = strictBounds.getNorthEast();

    // console.log('dragging', sw, ne, strictSw, strictNe)

    var swLng = sw.lng < strictSw.lng ? strictSw.lng : sw.lng,
      swLat = sw.lat < strictSw.lat ? strictSw.lat : sw.lat,
      neLng = ne.lng > strictNe.lng ? strictNe.lng : ne.lng,
      neLat = ne.lat > strictNe.lat ? strictNe.lat : ne.lat;
    if (swLng !== sw.lng || swLat !== sw.lat || neLng !== ne.lng || neLat !== ne.lat) {
      var newBounds = new BMap.Bounds(new BMap.Point(swLng, swLat), new BMap.Point(neLng, neLat));//sw西南,ne东北
      map.centerAndZoom(newBounds.getCenter(), map.getZoom());
    }
  });
}


function init(parentView, options) {
  parent = parentView;
  setData(options);
}

function getPoint(gpsStr) {
  if (gpsStr) {
    const arr = gpsStr.split(',');
    return new BMap.Point(Number(arr[0]), Number(arr[1]));
  }
  return null;
}


// 自定义覆盖物
function ComplexCustomOverlay(point, node) {
  this._point = point;
  this._node = node;
}

ComplexCustomOverlay.prototype = new BMap.Overlay();
ComplexCustomOverlay.prototype.initialize = function (map) {
  this._map = map;
  var div = this._div = document.createElement("div");
  div.style.position = "absolute";
  div.style.zIndex = BMap.Overlay.getZIndex(this._point.lat);

  var bgClor = '';
  var background = '';
  var width = 16;
  const nodeType = this._node.nodeType;
  if (nodeType === 'room') {
    bgClor = '#5BC0DE';
    background = 'radial-gradient(#fff, #5BC0DE)';
    width = 26;
  } else if (nodeType === 'gateway') {
    bgClor = '#e3f54d';
    background = 'radial-gradient(#fff, #e3f54d)';
    width = 20;
  } else if (nodeType === 'sub') {
    bgClor = 'green';
    background = 'radial-gradient(#fff, green)';
  } else {
    bgClor = 'green';
    background = 'radial-gradient(#fff, green)';
  }
  this._width = width;
  // div.style.backgroundColor = '#eee';
  div.style.background = background;
  div.style.cursor = 'pointer';
  div.style.boxSizing = 'border-box';
  div.style.border = "1px solid " + bgClor;
  div.style.boxShadow = "0 0 10px " + bgClor;

  div.style.borderRadius = width + 'px';
  div.style.height = width + 'px';
  div.style.width = width + 'px';
  div.style.userSelect = "none";
  div.style.zIndex = BMap.Overlay.getZIndex(this._point.lat) + 1;

  var that = this;
  div.addEventListener('mouseover', function (e, target) {
    showMyInfoWindow(e, getNodeTypeName(nodeType) + '：' + that._node.name);
  });
  div.addEventListener('mouseout', hideMyInfoWindow);

  map.getPanes().labelPane.appendChild(div);
  return div;
};
ComplexCustomOverlay.prototype.draw = function () {
  var map = this._map;
  var pixel = map.pointToOverlayPixel(this._point);
  this._div.style.left = (pixel.x - this._width / 2) + 'px';
  this._div.style.top = (pixel.y - this._width / 2) + 'px';
};

function addCustomMarker(point, node) {
  var marker = new ComplexCustomOverlay(point, node);
  map.addOverlay(marker);
  return marker;
}

function addMarker(name, point, nodeType) {
  var marker;
  var typeName = null;
  var img = null;
  if (nodeType === 'gateway') {
    typeName = '网关：';
    img = "../static/img/gateway.png";

  } else if (nodeType === 'sub') {
    typeName = '设备：';
    img = "../static/img/sub.png";

  } else if (nodeType === 'room') {
    typeName = '机房：';
    img = "../static/img/room.png";

  } else {
    typeName = '';
  }
  if (img) {
    var icon = new BMap.Icon(img, new BMap.Size(50, 50));
    marker = new BMap.Marker(point, {icon: icon});
  } else {
    marker = new BMap.Marker(point);
  }

  // 标签改为鼠标移动显示
  var infoWindow = new BMap.InfoWindow('', {
    title: '信息'
  });  // 创建信息窗口对象

  var label = new BMap.Label(name, {offset: new BMap.Size(20, -10)});
  label.setStyle({fontSize: '14px'});
  marker.setLabel(label);
  map.addOverlay(marker);
  return marker;
}

// 复杂的自定义覆盖物-告警闪烁
function AlarmOverlay(point, alarm, node) {
  this._point = point;
  this._alarm = alarm;
  this._node = node;
}

AlarmOverlay.prototype = new BMap.Overlay();
AlarmOverlay.prototype.initialize = function (map) {
  this._map = map;
  var div = this._div = document.createElement("div");
  div.className = ['alarmAnimation', 'alarmLv' + this._alarm.level].join(' ');
  div.style.zIndex = BMap.Overlay.getZIndex(this._point.lat) + 2;

  const that = this;
  div.addEventListener('mouseover', function(e, target) {
    let alarmLvName = ''
    if (that._alarm.level === 1) {
      alarmLvName = '紧急告警'
    } else if (that._alarm.level === 2) {
      alarmLvName = '主要告警'
    } else {
      alarmLvName = '一般告警'
    }
    let content = getNodeTypeName(that._node.nodeType) + '：' + that._node.name + '<br>' +
      alarmLvName + '：' + that._alarm.name
    showMyInfoWindow(e, content)
  })
  div.addEventListener('mouseout', hideMyInfoWindow);
  div.addEventListener("click", function () {
    // 跳转设备监控页面
    if (that._node.nodeType !== 'room') {
      parent.goDeviceView(that._node);
    } else {
      // 跳转机房监控页面
      parent.goRoomView(that._node);

    }
  });


  map.getPanes().labelPane.appendChild(div);
  return div;
};
AlarmOverlay.prototype.draw = function () {
  var map = this._map;
  var pixel = map.pointToOverlayPixel(this._point);
  this._div.style.left = (pixel.x - 20) + 'px';
  this._div.style.top = (pixel.y - 20) + 'px';
};

function getNodeTypeName(nodeType) {
  var typeName;
  if (nodeType === 'gateway') {
    typeName = '网关';

  } else if (nodeType === 'sub') {
    typeName = '设备';

  } else if (nodeType === 'room') {
    typeName = '机房';

  } else {
    typeName = '设备';
  }
  return typeName;
}

function showMyInfoWindow(e, content) {
  const myInfoWindow = document.getElementById('myInfoWindow');
  myInfoWindow.style.top = (e.clientY - 50) + 'px';
  myInfoWindow.style.left = (e.clientX + 10) + 'px';
  myInfoWindow.style.display = 'block';
  myInfoWindow.innerHTML = content;
}

function hideMyInfoWindow() {
  const myInfoWindow = document.getElementById('myInfoWindow');
  myInfoWindow.style.display = 'none';
}

function panTo(gpsPosition) {
  const p = getPoint(gpsPosition);
  map.panTo(p);
}

function setData(options) {
  data = options;

  roomMarker = null;
  deviceMarkers = [];
  alarmOverlaysMap = {};

  map.clearOverlays();

  const site = data.site;
  const room = data.room;
  const deviceList = data.deviceList;


  if (site && site.gpsPosition) {
    // 站点位置
    const sitePoint = getPoint(site.gpsPosition);
    roomMarker = addCustomMarker(sitePoint, site);

    //定位到以站点为中心
    map.panTo(sitePoint);
  }

  deviceList.filter(item => item.gpsPosition).forEach(device => {
    const point = getPoint(device.gpsPosition);
    const marker = addCustomMarker(point, device);
    deviceMarkers.push(marker);
    marker._div.addEventListener("click", function () {
      // 跳转设备监控页面
      if (device.nodeType !== 'room') {
        parent.goDeviceView(device);
      } else {
        // 跳转机房监控页面
        parent.goRoomView(device);

      }
    });

  })

}

function setAlarms(alarms) {
  // 清除告警效果
  Object.values(alarmOverlayMap).forEach(o => {
    map.removeOverlay(o);
  })
  alarmOverlayMap = {};

  alarms
    //.filter(alarm => alarm.level === 1) // 只显示紧急告警
    .forEach(alarm => {
      data.deviceList.forEach(node => {

        //如果有告警，添加告警闪烁
        const showDeviceAlarm = alarm.deviceCode === node.code && node.gpsPosition; // 在设备上显示告警
        const showRoomAlarm = node.nodeType==='room' && alarm.roomId === node.id && node.gpsPosition; //在机房上显示告警

        // 获取告警maker的坐标点
        let point = null;
        if (showDeviceAlarm || showRoomAlarm) {
          point = getPoint(node.gpsPosition);
        }

        if( point ){
          const key = node.nodeType + '-' + node.id;

          // 一个点只添加最高级别的告警闪烁
          if(!alarmOverlayMap[key] || alarmOverlayMap[key]._alarm.level > alarm.level ){
            const alarmOverlay = new AlarmOverlay(point, alarm, node);
            alarmOverlayMap[key] = alarmOverlay;

            map.addOverlay(alarmOverlay);
          }

        }
      })
    });

}
